import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from "element-plus";
import { useTokenStore } from "@/stores/useTokenStore";
import Dashboard from '@/views/admin/Dashboard.vue';

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login.vue"),
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/AdminLayout.vue'), // 整个后台布局
    meta: { requiresAuth: true },
    redirect: '/home/index',
    children: [
      {
        path: 'index',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '首页' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/admin/UsersView.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'roles',
        name: 'Roles',
        component: () => import('@/views/admin/UserRolesView.vue'),
        meta: { title: '角色管理' }
      },
      {
        path: 'tags',
        name: 'Tags',
        component: () => import('@/views/admin/TagsListView.vue'),
        meta: { title: '标签管理' }
      },
      {
        path: 'stores',
        name: 'Store',
        component: () => import('@/views/admin/StoresListView.vue'),
        meta: { title: '门店管理' }
      },
      {
        path: 'storeaddresses',
        name: 'StoreAddresses',
        component: () => import('@/views/admin/StoreAddressesView.vue'),
        meta: { title: '门店地址管理' }
      },
      {
        path: 'rolePermissions',
        name: 'RolePermissions',
        component: () => import('@/views/admin/AccessControl.vue'),
        meta: { title: '权限管理' }
      },
      {
        path: 'categories',
        name: 'Categories',
        component: () => import('@/views/admin/CategoriesListView.vue'),
        meta: { title: '分类管理' }
      },
      {
        path: 'brands',
        name: 'Brands',
        component: () => import('@/views/admin/BrandsListView.vue'),
        meta: { title: '品牌管理' }
      },
      {
        path: 'activityLogs',
        name: 'ActivityLogs',
        component: () => import('@/views/admin/ActivityLogsView.vue'),
        meta: { title: '日志管理' }
      }
      , {
        path: 'products',
        name: 'Products',
        component: () => import('@/views/admin/ProductsListView.vue'),
        meta: { title: '商品管理' }
      }, {
        path: 'sku',
        name: 'SKU',
        component: () => import('@/views/admin/SkuListView.vue'),
        meta: { title: 'SKU管理' }

      }, {
        path: 'spu',
        name: 'SPU',
        component: () => import('@/views/admin/SpuListView.vue'),
        meta: { title: 'SPU管理' }
      },
      {
        path: 'banners',
        name: 'Banners',
        component: () => import('@/views/admin/BannersView.vue'),
        meta: { title: 'banner管理' }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('@/views/admin/OrdersView.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: 'orders/detail/:id',
        name: 'OrderDetail',
        component: () => import('@/views/admin/OrderDetailView.vue'),
        meta: { title: '订单详情' }
      },
      {
        path: 'riders',
        name: 'Riders',
        component: () => import('@/views/admin/RidersView.vue'),
        meta: { title: '骑手管理' }
      },
      {
        path: 'riders/detail/:id',
        name: 'RiderDetail',
        component: () => import('@/views/admin/RiderDetailView.vue'),
        meta: { title: '骑手详情' }
      },
      {
        path: '/home/products/:id',
        name: 'ProductDetail',
        component: () => import('../views/admin/ProductDetailView.vue'),
        meta: { title: '商品详情', requiresAuth: true }
      }
    ]
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return {
        ...savedPosition,
        behavior: 'smooth'
      }
    }

    if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth',
        top: 70
      }
    }

    return {
      top: 0,
      behavior: 'smooth'
    }
  }
});

// 全局导航守卫：若访问需要登录的页面且未登录，则重定向到 /login
router.beforeEach((to, from, next) => {
  const authStore = useTokenStore()
  console.log('路由导航:', to.path, '是否需要认证:', to.meta.requiresAuth, '是否有token:', !!authStore.token);

  // 尝试从localStorage读取token作为备份
  let hasToken = !!authStore.token;
  if (!hasToken) {
    try {
      const savedToken = JSON.parse(localStorage.getItem('token'));
      if (savedToken && savedToken.token) {
        console.log('在localStorage中找到token备份，正在恢复...');
        // 恢复token到store
        authStore.setToken(savedToken.token);
        hasToken = true;
      }
    } catch (e) {
      console.error('读取localStorage中的token失败', e);
    }
  }

  if (to.meta.requiresAuth && !hasToken) {
    console.log('未登录，重定向到登录页面');
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router;
